import {
  dicts,
  drawerFormState,
  userFormState,
  expandLoading,
  intentionMap,
  isExpand,
  popularLevelOptions,
} from "./store";
import pinia from "@/store/store";
import { tableLoading } from "./table";
const dictsStore = useDictsStore(pinia);
export const fetchInfo = async (params = {}) => {
  const res: any = await popularApi.queryDataById(params);
  const {
    data: { popularLevel = [] },
  } = res;
  popularLevelOptions.value = arrayToOptions(popularLevel, {
    label: "name",
    value: "level",
  });
};
export const fetchDicts = (dicts = ref<any>({}), params: any = {}) =>
  new Promise(async (resolve) => {
    const res = await userApi.queryDicts(params);
    dicts.value = res.data ?? {};
    intentionMap.value = arrayToOptions(res?.data?.intention ?? []);
    dictsStore.setState(res.data ?? {});
    resolve(storeToRefs(dictsStore).getState.value);
  });
export const fetchDataById = async (params = {}) => {
  try {
    tableLoading.value = true;
    const res: any = await authApi.queryDataById(params);
    const { data } = res;
    initObjAttr(drawerFormState, data, "target");
    drawerFormState.account_picture = Array(4).fill("");
    drawerFormState.account_picture = drawerFormState.account_picture.map(
      (item, index) => data?.account_picture[index]?.url || ""
    );
    return res;
  } catch (error: any) {
    message.error(error.message);
  } finally {
    tableLoading.value = false;
  }
};

export const fetchPopularDataById = async (params = {}) => {
  try {
    tableLoading.value = true;
    const res: any = await authApi.queryPopularDataById(params);
    const { data } = res;
    initObjAttr(drawerFormState, data, "target");
    const tmpIntention =
      dicts.value?.intention?.map(({ name, id }) => {
        return {
          label: name,
          value: id,
        };
      }) ?? [];
    drawerFormState.intention = drawerFormState.intention
      .split(",")
      .map((item) => selectDictLabel(tmpIntention, item));
    drawerFormState.account_picture = Array(4).fill("");
    drawerFormState.account_picture = drawerFormState.account_picture.map(
      (item, index) => data?.account_picture[index]?.url || ""
    );
    return res;
  } catch (error: any) {
    message.error(error.message);
  } finally {
    tableLoading.value = false;
  }
};

const fetchUserDataById = async (record: { uid: any }) => {
  const res: any = await userApi.queryDataById({
    userId: record.uid,
  });
  initObjAttr(userFormState, res.data, "target");
};
export const handleExpand: any = async (record: { uid: any }, event: any) => {
  event.stopPropagation();
  isExpand.value = !isExpand.value;
  if (isExpand.value) {
    expandLoading.value = true;
    await fetchUserDataById(record);
    expandLoading.value = false;
  } else {
  }
};
